<?php
class SiteController extends ControllerBase {

	public function init(){
		Yii::app()->theme = SITE_THEME;
		parent::init();
	}
	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return CMap::mergeArray(parent::filters(),array(
			'accessControl', // perform access control for CRUD operations
		));
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'users'=> array_merge(Util::getMember(), Util::getSuperMods()),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
    public function actionIndex($category = null) {
    	$model 			= new Announcement();
    	$userId		= (Util::isMember()) ? Yii::app()->user->id : '';
    	$announcements 	= $model->getList($userId, $category);
		$this->render('index', compact('announcements'));
    }

 	public function actionSearch() {
    	$model 			= new Announcement();

    	$key	= isset($_POST['key_search']) ? $_POST['key_search'] : '';
    	$announcements 	= $model->searchPost($key);
		$this->render('search', compact('announcements', 'key'));
    }

	public function actionView($id) {
		$model 		= new Announcement();
		$objAsign	= new AnnouncementAssign();

		$userId		= (Util::isMember()) ? Yii::app()->user->id : '';

		// Accept invite
		if (isset($_POST['accept'])) {
			$objAsign->setAsign($id, $userId, 2);
		}
		// Unaccept invite
		else if (isset($_POST['unaccept'])) {
			$objAsign->setAsign($id, $userId, 1, $_POST['unaccept']);
		}

		// Set view
		self::reloadAnnouncement($id);

    	// Load data
    	$data 	= $model->getContent($id);

    	// Check invite
    	$checkAsign = false;
    	if ($data->event_fg == 1 && $userId != '' && $data->event_end_date >= date('Y-m-d H:i:s')) {
    		$checkAsign	= $objAsign->checkAsign($id, $userId);
    	}

		$this->render('view', compact('data', 'checkAsign'));
    }

    protected function reloadAnnouncement($id){
		$userId 				= Yii::app()->user->id;
		if ($userId != '') {
			$condition				= array('announcement_id' => $id, 'member_id' => $userId);
			// Check exits
			$announcementAssign	= AnnouncementAssign::model()->findByAttributes($condition);

			// Set member view announcement
			if (isset($announcementAssign->id)) {
				$announcementAssign->attributes = $announcementAssign->attributes;
				$announcementAssign->view_fg	= 1;
				$announcementAssign->save();
			}
		}
    }
    public function actionLoadFormReply() {
    	echo $this->widget('application.components.CommentPost', array('id' => $_GET['post_id'], 'ajax' => true), true);
		exit;
    }

  	public function actionSubmitComment() {
		if (isset($_POST['content']) && $_POST['content'] != '') {
			$objComments	= new Comments();
			$objComments->attributes 	= $_POST;
			$objComments->create_at		= date("Y-m-d H:i:s");
			$objComments->insert();

			echo $this->widget('application.components.CommentPost', array('info' => array(
				'ajax'		=> true,
				'isReply' 	=> ($objComments->parent_id == '' ? false : true),
				'name' 		=> Util::getUserComment($objComments),
				'date' 		=> Util::formatTime($objComments->create_at, true, '-'),
				'content' 	=> $objComments->content,
				'commentId'	=> $objComments->id,
			)), true);
		}
		exit;
	}
    public function actionError() {
        if ($error = Yii::app()->errorHandler->error) {
            if (Yii::app()->request->isAjaxRequest)
                echo $error['message'];
            else
                $this->render('error', $error);
        }
    }

    public function actionLanguages($lang) {
        $language = isset($_GET['lang']) ? $_GET['lang'] : Yii::app()->language;
        Yii::app()->request->cookies['language'] = new CHttpCookie('language', $lang);
        $this->redirect($_SERVER['HTTP_REFERER']);
    }

    public function actionLogout() {
        if (Yii::app()->user->isGuest) {
            $this->redirect(Yii::app()->homeUrl);
        }
        Yii::app()->user->logout();
        $this->redirect(Yii::app()->homeUrl);
    }

    public function actionIntro(){
        $this->render('intro');
    }

    public function actionContact(){
        $this->render('contact');
    }

    public function actionService(){
        $this->render('service');
    }

    public function actionAnouncement(){
        $this->render('anouncement');
    }

    public function actionForgotPassword() {
        if (!(Yii::app()->user->isGuest))
            $this->redirect(Yii::app()->homeUrl);

        $this->layout = '//layouts/0-1-0/1';
        Yii::import('application.modules.user.models.Recovery');
        $model = new Recovery;

        if (isset($_POST['Recovery'])) {
            $model->attributes = $_POST['Recovery'];
            if ($model->validate()) {
                // Update new password
                $newPassword = Recovery::generatePassword();
                $user = User::model()->findByPk($model->uid);
                $user->password = md5($newPassword);
                $user->update('password');

                Yii::import('ext.mail.YiiMailMessage');
                $message = new YiiMailMessage;

                // message notice change password
                $subject = TranslateUtil::t('Spring Candy - Forgot Password');
                $body = CHtml::tag('p', array(), "Hi {$user->username},");
                $body .= CHtml::tag('p', array(), "Password for {$user->username} has been reset.");
                $body .= CHtml::tag('p', array(), "Here's all the information you need to get you started .");

                $body .= CHtml::tag('p', array(), "------------------------------<br/>", false);
                $body .= 'Login Infomation';
                $body .= "------------------------------<br/>";
                $body .= "User ID: {$user->username}<br/>";
                $body .= "Password: {$newPassword}<br/>";
                $body .= CHtml::closeTag('p');

                $message->setSubject($subject);
                $message->setBody($body, 'text/html', 'utf8');

                $message->setFrom(array('admin@springcandy.com' => 'Spring Candy Webmaster'));
                $message->setReplyTo(array('admin@springcandy.com' => 'Spring Candy Webmaster'));

                // Recipient
                $recipients = array($user->email);
                $message->setTo($recipients);

                // Send mail
                if (Yii::app()->mail->send($message)) {
                    $this->setFlash(TranslateUtil::t('Password has been reset for {0}', array('{0}' => $user->username)), SiteController::FLASH_SUCCESS);
                    $this->refresh();
                }
            }
        }
        $this->render('recovery', array('model' => $model));
    }
}